package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.his.domain.*;
import com.ruoyi.his.domain.vo.PreVo;
import com.ruoyi.his.domain.vo.VisitQuery;
import com.ruoyi.his.domain.vo.VisitVo;
import com.ruoyi.his.domain.vo.medicinesVo;
import com.ruoyi.his.mapper.*;
import com.ruoyi.system.domain.vo.HisHospitalNationVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.HisHospitalNationMapper;
import com.ruoyi.system.domain.HisHospitalNation;
import com.ruoyi.system.service.IHisHospitalNationService;

/**
 * 国家机构Service业务层处理
 *
 * @author Alan
 * @date 2024-03-07
 */
@Service
public class HisHospitalNationServiceImpl implements IHisHospitalNationService
{
    @Autowired
    private HisDepartmentMapper hisDepartmentMapper;
    @Autowired
    private HisHospitalNationMapper hisHospitalNationMapper;
    @Autowired
    private OdsHospitalDataMapper odsHospitalDataMapper;

    @Autowired
    OdsHospitalAllMapper odsHospitalAllMapper;

    @Autowired
    private OdsDoctorDataMapper odsDoctorDataMapper;

    @Autowired
    private OdsDoctorAllMapper odsDoctorAllMapper;
    @Value("${http.url}")
    private String url;
    /**
     * 查询国家机构
     *
     * @param uniqueCode 国家机构主键
     * @return 国家机构
     */
    @Override
    public HisHospitalNation selectHisHospitalNationByUniqueCode(Integer uniqueCode)
    {
        return hisHospitalNationMapper.selectHisHospitalNationByUniqueCode(uniqueCode);
    }

    /**
     * 查询国家机构列表
     *
     * @param hisHospitalNation 国家机构
     * @return 国家机构
     */
    @Override
    public List<HisHospitalNation> selectHisHospitalNationList(HisHospitalNation hisHospitalNation)
    {
        return hisHospitalNationMapper.selectHisHospitalNationList(hisHospitalNation);
    }

    /**
     * 新增国家机构
     *
     * @param hisHospitalNation 国家机构
     * @return 结果
     */
    @Override
    public int insertHisHospitalNation(HisHospitalNation hisHospitalNation)
    {
        return hisHospitalNationMapper.insertHisHospitalNation(hisHospitalNation);
    }

    /**
     * 修改国家机构
     *
     * @param hisHospitalNation 国家机构
     * @return 结果
     */
    @Override
    public int updateHisHospitalNation(HisHospitalNation hisHospitalNation)
    {
        return hisHospitalNationMapper.updateHisHospitalNation(hisHospitalNation);
    }

    /**
     * 批量删除国家机构
     *
     * @param uniqueCodes 需要删除的国家机构主键
     * @return 结果
     */
    @Override
    public int deleteHisHospitalNationByUniqueCodes(Integer[] uniqueCodes)
    {
        return hisHospitalNationMapper.deleteHisHospitalNationByUniqueCodes(uniqueCodes);
    }

    /**
     * 删除国家机构信息
     *
     * @param uniqueCode 国家机构主键
     * @return 结果
     */
    @Override
    public int deleteHisHospitalNationByUniqueCode(Integer uniqueCode)
    {
        return hisHospitalNationMapper.deleteHisHospitalNationByUniqueCode(uniqueCode);
    }

    @Override
    public Map getlist(List<String> hospitalIds, List<String> signatures) {
        Map map = hisHospitalNationMapper.getlist(hospitalIds, signatures);
        int totalDepartment =0;
        List<HisDepartment> gettotle = hisHospitalNationMapper.gettotle(hospitalIds, signatures);
        for(HisDepartment hisDepartment : gettotle){
            if(hisDepartment.getDeviceId()!=null && hisDepartment.getDeviceId()!="") {
                String[] s = hisDepartment.getDeviceId().split(",");
                totalDepartment += s.length;
            }
        }
        map.put("totalDepartment",totalDepartment);
        return map;
    }

    @Override
    public List<HisHospitalNationVo> selectHisHospitalNationLists(HisHospitalNation hisHospitalNation) {
        List<HisHospitalNationVo> hisHospitalNationVos = hisHospitalNationMapper.selectHisHospitalNationLists(hisHospitalNation);
        for (HisHospitalNationVo nationVo:hisHospitalNationVos){
            if("2".equals(nationVo.getType())){
                HisHospitalNation hisHospitalNation1 = hisHospitalNationMapper.selectOne(new LambdaQueryWrapper<HisHospitalNation>()
                        .eq(HisHospitalNation::getRegisterNumber, nationVo.getNumber()));
                if(hisHospitalNation1.getEnabled()!=null){
                    nationVo.setEnabled(hisHospitalNation1.getEnabled());
                    nationVo.setMedicalSpecialtiesCode(hisHospitalNation1.getMedicalSpecialtiesCode());
                }
            }
            if(StringUtils.isNotBlank(nationVo.getMedicalSpecialtiesCode())){
                String[] split = nationVo.getMedicalSpecialtiesCode().split("/");
                nationVo.setMedicalSpecialtiesValue(split.length);
            }
        }

        return hisHospitalNationVos;
    }


    @Override
    public JSONObject selectListVisit(VisitQuery visitQuery, Integer pageNum, Integer pageSize) {
        String str="pageNumber="+pageNum+"&pageSize="+pageSize+"&time="+visitQuery.getTime()+"";
        if(StringUtils.isNotBlank(visitQuery.getClinicId())){
            str+="&clinicId="+visitQuery.getClinicId()+"";
        }
        if (StringUtils.isNotBlank(visitQuery.getHospitalIds())){
            str+="&hospitalId="+visitQuery.getHospitalIds()+"";
        }
        if (StringUtils.isNotBlank(visitQuery.getSignatures())){
            str+="&signature="+visitQuery.getSignatures()+"";
        }
        String string = HttpUtils.sendGet(url+"/clinic/query", str);
        AjaxResult visitVos = JSONObject.parseObject(string, AjaxResult.class);
        JSONObject data = (JSONObject) visitVos.get("data");
        JSONArray list = data.getJSONArray("list");
        Long total = data.getLong("total");
        List<VisitVo> javaList = list.toJavaList(VisitVo.class);
        for (VisitVo vo:javaList){
            if(StringUtils.isNotBlank(vo.getSignature()) && StringUtils.isNotBlank(vo.getHospital_id())){
                OdsHospitalAll odsHospitalData = odsHospitalAllMapper.selectBySigAndHosId(vo.getSignature(), vo.getHospital_id());
                if(Objects.nonNull(odsHospitalData)){
                    vo.setHospitalName(odsHospitalData.getInstitutionName());
                }
                if (StringUtils.isNotBlank(vo.getRegister_number())){
                final List<HisDepartment> hisDepartments = hisDepartmentMapper.selectList(new LambdaQueryWrapper<HisDepartment>()
                        .eq(HisDepartment::getRegisterNumber, vo.getRegister_number()));
                int totals = 0;
                for (HisDepartment department:hisDepartments){
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(department.getDeviceId())){
                        String[] split = department.getDeviceId().split(",");
                        totals += split.length;
                    }
                }
                vo.setTotal(totals);
               }
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",javaList);
        jsonObject.put("total",total);
        return jsonObject;
    }


    @Override
    public JSONObject selectListPre(VisitQuery visitQuery, Integer pageNum, Integer pageSize) {
        String str="pageNumber="+pageNum+"&pageSize="+pageSize+"&time="+visitQuery.getTime()+"";
        if(StringUtils.isNotBlank(visitQuery.getPreId())){
            str+="&preId="+visitQuery.getPreId()+"";
        }
        if (StringUtils.isNotBlank(visitQuery.getHospitalIds())){
            str+="&hospitalId="+visitQuery.getHospitalIds()+"";
        }
        if (StringUtils.isNotBlank(visitQuery.getSignatures())){
            str+="&signature="+visitQuery.getSignatures()+"";
        }
        String string = HttpUtils.sendGet(url+"/pre/query", str);
        AjaxResult visitVos = JSONObject.parseObject(string, AjaxResult.class);
        JSONObject data = (JSONObject) visitVos.get("data");
        JSONArray list = data.getJSONArray("list");
        Long total = data.getLong("total");
        List<PreVo> javaList = list.toJavaList(PreVo.class);
        String strValue="";
        for (PreVo vo:javaList){
            strValue+= vo.getClinic_id()+",";
        }
        String strs = HttpUtils.sendGet(url+"/clinic/get", "clinicIds="+strValue+"");
        AjaxResult re = JSONObject.parseObject(strs, AjaxResult.class);
        JSONObject array = (JSONObject) re.get("data");
        for (PreVo vo:javaList){
            VisitVo visitVo = array.getObject(vo.getClinic_id(),VisitVo.class);
            vo.setDepartmentName(visitVo.getDepartment_name());
            vo.setPatientName(visitVo.getPatient_name());
            if(StringUtils.isNotBlank(vo.getSignature()) && StringUtils.isNotBlank(vo.getHospital_id())){
//                OdsHospitalAll odsHospitalData = odsHospitalAllMapper.selectRegisterNumber(vo.getRegister_number());
                OdsHospitalAll odsHospitalData = odsHospitalAllMapper.selectBySigAndHosId(vo.getSignature(), vo.getHospital_id());
                if(Objects.nonNull(odsHospitalData)){
                    vo.setHospitalName(odsHospitalData.getInstitutionName());
                }
                if(StringUtils.isNotBlank(vo.getRegister_number())) {
                    final List<HisDepartment> hisDepartments = hisDepartmentMapper.selectList(new LambdaQueryWrapper<HisDepartment>()
                            .eq(HisDepartment::getRegisterNumber, vo.getRegister_number()));
                    int totals = 0;
                    for (HisDepartment department : hisDepartments) {
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(department.getDeviceId())) {
                            String[] split = department.getDeviceId().split(",");
                            totals += split.length;
                        }
                    }
                    vo.setTotal(totals);
                }
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",javaList);
        jsonObject.put("total",total);
        return jsonObject;
    }

    @Override
    public PreVo selectPre(String visitQuery) {
        String strs = HttpUtils.sendGet(url+"/clinic/get", "clinicIds="+visitQuery+"");
        AjaxResult re = JSONObject.parseObject(strs, AjaxResult.class);
        JSONObject array = (JSONObject) re.get("data");
        PreVo preVo = array.getObject(visitQuery,PreVo.class);
            if(StringUtils.isNotBlank(preVo.getSignature()) && StringUtils.isNotBlank(preVo.getHospitalId())){
                OdsHospitalAll odsHospitalAll = odsHospitalAllMapper.selectBySigAndHosId(preVo.getSignature(), preVo.getHospitalId());
            preVo.setHospitalName(odsHospitalAll.getInstitutionName());
        }
            if (StringUtils.isNotBlank(preVo.getDoctorCode())){
                OdsDoctorAll odsDoctorAll = odsDoctorAllMapper.selectOne(new LambdaQueryWrapper<OdsDoctorAll>().eq(OdsDoctorAll::getDoctorCode, preVo.getDoctorCode()));
                preVo.setIdCard(odsDoctorAll.getIdCard());
            }
            if (!preVo.getMedicines().isEmpty()){
                BigDecimal sum = BigDecimal.ZERO;
                for (medicinesVo medicine : preVo.getMedicines()) {
                    BigDecimal price = new BigDecimal(medicine.getPrice());
                    sum=sum.add(price);
                }
                BigDecimal sumPrice = sum.setScale(3, BigDecimal.ROUND_HALF_UP);
                double v = sumPrice.doubleValue();
                preVo.setTotalPrice(String.valueOf(v));
            }
        return preVo;
    }

    @Override
    public HisHospitalNation getinfo(String registerNumber) {
        return hisHospitalNationMapper.selectOne(new LambdaQueryWrapper<HisHospitalNation>()
                .eq(HisHospitalNation::getRegisterNumber,registerNumber));
    }
}
